import 'package:badges/badges.dart' as badges;
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_views/jr_home/jr_activity_post_view.dart';
import 'package:jet_rails/jr_app/jr_views/jr_home/jr_home_controller.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_activity_widget.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_snippet.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';

class JrHomeView extends StatefulWidget {
  final String title;

  const JrHomeView({super.key, required this.title});

  @override
  State<JrHomeView> createState() => _JrHomeViewsState();
}

class _JrHomeViewsState extends State<JrHomeView> {
  late JrHomeController controller;
  late EasyRefreshController easyRefreshController;

  @override
  void initState() {
    super.initState();
    controller = Get.put(JrHomeController());
    easyRefreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  @override
  void dispose() {
    Get.delete<JrHomeController>();
    easyRefreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
            decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color(0xFF16192B),
              Color(0xFF2872B7),
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        )),
        SafeArea(
          child: Padding(
              padding: EdgeInsets.only(top: 10.h, left: 16.w, right: 16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 44.h,
                    padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 16.w),
                    child: Text('JetRails', style: const TextStyle(fontSize: 24).merge(JrSnippets.commonTextStyle)),
                  ),
                  GestureDetector(
                    onTap: () {
                      Get.to(() => const JrActivityPostView());
                    },
                    child: SizedBox(
                      child: Stack(
                        children: [
                          Image.asset('assets/images/img_create_event_bg.png'),
                          Positioned(
                              right: 10,
                              top: 17,
                              child: badges.Badge(
                                  ignorePointer: true,
                                  badgeStyle: const badges.BadgeStyle(badgeColor: Colors.transparent),
                                  position: badges.BadgePosition.topEnd(top: -15.h, end: 25.w),
                                  badgeContent: const CostBadge(mirrorBg: true),
                                  child: Image.asset('assets/webp/icon_post.webp', height: 36.h)))
                        ],
                      ),
                    ),
                  ),
                  Expanded(child: getBody())
                ],
              )),
        )
      ],
    );
  }

  Widget getBody() {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: EasyRefresh(
        controller: easyRefreshController,
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 2));
          easyRefreshController.finishRefresh(IndicatorResult.success);
        },
        onLoad: () async {
          await Future.delayed(const Duration(seconds: 2));
          easyRefreshController.finishLoad(IndicatorResult.noMore);
        },
        child: Obx(() {
          final list = Get.find<JrServices>().availableActivity;
          return ListView.builder(
            padding: const EdgeInsets.only(top: 0),
            itemCount: list.length,
            itemBuilder: (context, index) {
              var item = list.elementAt(index);
              return JrActivityWidget(
                  activityModel: item,
                  action: !JrServices.instance.isMe(item.author?.userId ?? '')
                      ? JrStyledButton(
                          text: item.joined ? 'Withdraw' : 'Participate',
                          onTap: () => Get.dialog(
                              Center(
                                child: Container(
                                  height: 170.h,
                                  width: 320.w,
                                  padding: EdgeInsets.symmetric(horizontal: 24.h, vertical: 32.w),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10.r),
                                      image: const DecorationImage(
                                          alignment: Alignment.bottomCenter,
                                          image: AssetImage('assets/webp/img_activity_widget_bg.webp'),
                                          fit: BoxFit.fitWidth)),
                                  child: Column(
                                    children: [
                                      Text(
                                        'Are you sure you want to ${item.joined ? 'withdraw from' : 'register for'} this event?',
                                        style: const TextStyle(color: Colors.white),
                                      ),
                                      SizedBox(height: 24.h),
                                      JrStyledButton(
                                          text: item.joined ? 'Withdraw' : 'Participate',
                                          onTap: () {
                                            final joined = item.joined;
                                            controller.toggleJoinStatus(item);
                                            Get.back();
                                            JrToast.show(joined ? 'Cancel success' : 'Successfully participated');
                                          })
                                    ],
                                  ),
                                ),
                              ),
                              transitionDuration: const Duration(milliseconds: 100)),
                        )
                      : Container());
            },
          );
        }),
      ),
    );
  }
}
